/*
 * @lc app=leetcode.cn id=738 lang=javascript
 *
 * [738] 单调递增的数字
 */

// @lc code=start
/**
 * @param {number} N
 * @return {number}
 */
var monotoneIncreasingDigits = function (N) {
  const nums = N.toString()
    .split('')
    .map((v) => Number(v));

  let idx = -1;
  let max = -1;

  for (let i = 0; i < nums.length - 1; i++) {
    if (max < nums[i]) {
      max = nums[i];
      idx = i;
    }

    if (nums[i] > nums[i + 1]) {
      nums[idx]--;
      for (let j = idx + 1; j < nums.length; j++) {
        nums[j] = 9;
      }
    }
  }

  return Number(nums.join(''));
};
// @lc code=end
